/**   
* @Title: CashierAesUtils.java 
* @Package cn.com.gome.common.security.aes 
* @Description: 收银台数据库存储AES加解密
* @author chenmin-ds   
* @date 2015年5月13日 下午2:19:53 
* @company cn.com.gome
* @version V1.0   
*/ 


package com.gomeplus.security.aes;

import java.security.Key;
import java.security.SecureRandom;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;

import com.gomeplus.security.base64.Base64Util;

/** 
 * @ClassName: CashierAesUtils 
 * @Description: 收银台数据库存储AES加解密
 * @author chenmin-ds 
 * @date 2015年5月13日 下午2:19:53  
 */
public class CashierAesUtils {
	
	private static String keyStr = "wwwgomeholdingscom";
	
	private static String charset="utf-8";
	
	private static Key key = null;
	
	private static String[] g = new String[4];

	public static String encryptStr(String value){
		String valueSecurity = encodeMessage(value);
		String[] l = new String[4];
		int sum = valueSecurity.length()/4;
		for(int i=0;i<4;i++){
			l[i] = valueSecurity.substring(i*sum, sum*(i+1));
		}
		StringBuffer sb = new StringBuffer();
		for(int i=2;i>=0;i--){
			sb.append(l[i]+g[i]);
		}
		sb.append(g[3] + l[3]);
		return sb.toString();
	}
	
	public static String decryptStr(String value){
		String[] l = new String[4];
		int sum = value.length()/4;
		for(int i=0;i<4;i++){
			l[i] = value.substring(i*sum, sum*(i+1));
		}
		StringBuffer sb = new StringBuffer();
		for(int i=2;i>=0;i--){
			sb.append(l[i].substring(0, l[i].length()-1));
		}
		value = sb.append(l[3].substring(1, l[3].length())).toString();
		return decodeMessage(value);
	}
	
	static{
		try {
			KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");
			SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG","SUN");
			secureRandom.setSeed(keyStr.getBytes());
			keyGenerator.init(secureRandom);
			key = keyGenerator.generateKey();
			int a = 0;
			for(int i=0;i<4;i++){
				a = i*4;
				if(a>keyStr.length()){
					a = 0;
				}
				g[i] = String.valueOf(keyStr.charAt(i*4));
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	private static String encodeMessage(String message){
		String result = null;
		try {
			Cipher cipher = Cipher.getInstance("AES");
			cipher.init(Cipher.ENCRYPT_MODE, key);
			byte[] temp = cipher.doFinal(message.getBytes(charset));
			result = Base64Util.encodeMessage(temp);
		}catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}
	private static String decodeMessage(String message){
		String result = null;
		try {
			Cipher cipher = Cipher.getInstance("AES");
			cipher.init(Cipher.DECRYPT_MODE, key);
			byte[] temp = cipher.doFinal(Base64Util.decodeMessage(message));
			result = new String(temp,charset);
		}catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}
	
}
